# server/src/knowledge/routes.py
# API路由
from fastapi import APIRouter, UploadFile, File, Form
from fastapi.responses import JSONResponse
from .exceptions import FileParseError
from config import Config

router = APIRouter(tags=["Knowledge Base"])

class DocumentResponse(BaseModel):
    id: int
    filename: str
    file_type: str
    created_at: str

@router.post("/api/knowledge/upload")
async def upload_document(
    file: UploadFile = File(...),
    metadata: str = Form("{}")
):
    """上传文档到知识库"""
    try:
        provider = await Config.get_knowledge_provider()
        doc_id = await provider.add_document(
            await file.read(),
            file.filename,
            json.loads(metadata)
        )
        return JSONResponse(
            {"status": "success", "doc_id": doc_id},
            status_code=201
        )
    except FileParseError as e:
        return JSONResponse(
            {"error": str(e)},
            status_code=400
        )

@router.delete("/api/knowledge/{doc_id}")
async def delete_document(doc_id: int):
    """删除文档"""
    provider = await Config.get_knowledge_provider()
    success = await provider.delete_document(doc_id)
    return {"status": "success" if success else "failed"}

@router.get("/api/knowledge/documents")
async def list_documents(page: int = 1, page_size: int = 10):
    """列出所有文档"""
    provider = await Config.get_knowledge_provider()
    docs = await provider.list_documents(page, page_size)
    return {"data": docs}